package util;

import groove.GrooveClient;
import groove.json.util.SongInfo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;
import java.text.DecimalFormat;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;

import com.example.myfirstapp.R;

public class GrooveClientDownloadTask extends
		AsyncTask<Void, Void, Void> {

	private Context context;
	private GrooveClient client;
	private SongInfo song;
	private int ID;
	private NotificationManager notificationManager;
	private NotificationCompat.Builder builder;
	private float currentlyDownloadedBytes = 0f;
	private float sizeOfFile = 0f;
	private DecimalFormat df;
	

	public GrooveClientDownloadTask(Activity context, GrooveClient client, SongInfo song) {
		this.context = context;
		this.client = client;
		this.song = song;
		this.ID = Helper.getNotificationID();
		this.df =   new DecimalFormat  ( "0.00" );
	}
	
	
	@Override
	protected void onPreExecute() {
		createNotification();
	}

	@Override
	protected void onPostExecute(Void result) {
		builder.setContentTitle("Downloaded " + song.getSongName()).setContentText("Saved at ../Music/" + song.getSongName() + ".mp3");
		notificationManager.notify(this.ID, builder.build());
	}

	@Override
	protected Void doInBackground(Void... params) {
		downloadSong();
		return null;
	}
	
	public void createNotification() {
		 builder = new Builder(context)
		 			.setSmallIcon(R.drawable.song)
			        .setContentTitle("Downloading " + song.getSongName())
			        .setContentText(getNotificationString());
		 
		 notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		 notificationManager.notify(this.ID, builder.build());
		 
    }
	
	private String getNotificationString(){
		float oneMB = 1024*1024;
		float currentSize = currentlyDownloadedBytes /oneMB;
		float completeSize = sizeOfFile / oneMB;
		
		
		
	    return df.format(currentSize) + "MB / " + df.format(completeSize) + "MB downloaded";           
	}
	
	public void updateNotification(){
		builder.setContentText(getNotificationString());
		notificationManager.notify(this.ID, builder.build());
	}
	
	private void downloadSong() {
        File SDCardRoot = Environment.getExternalStorageDirectory();
        File file = new File(SDCardRoot,"Music/" + song.getSongName() + ".mp3");
       
        //Erst mal alles platt machen
        if(file.exists()){
        	file.delete();
        }
        
        //Dann neue Datei erstellen
        FileOutputStream fileOutput = null;
        try {
        	file.createNewFile();
        	fileOutput = new FileOutputStream(file);
        	URLConnection connection = client.getSongStream(song);
        	
        	sizeOfFile = connection.getContentLength();
        	InputStream inputStream = connection.getInputStream();
        	byte[] buffer = new byte[(int) sizeOfFile];
        	
        	int bytesRead = 0; 
        	float lastUpdateByteSum = 0;

        	while ( (bytesRead = inputStream.read(buffer)) > 0 ) {
        		fileOutput.write(buffer, 0, bytesRead);
        		currentlyDownloadedBytes += bytesRead;
        		if((currentlyDownloadedBytes-lastUpdateByteSum) > 102400 /*100 KB Schritte ansonsten leidet der Downloadspeed zu sehr*/){
        			updateNotification();
        			lastUpdateByteSum = currentlyDownloadedBytes;
        		}
        		
        	}
        	
        	fileOutput.close();
        } catch (IOException e) {
        	e.printStackTrace();
        	return;
        }
	}

}
